package com.ruoyi.system.controller;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Blob;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.Xtree;
import jdk.nashorn.internal.objects.Global;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Ytendereqe;
import com.ruoyi.system.service.IYtendereqeService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 招标需求Controller
 *
 * @author ruoyi
 * @date 2024-04-03
 */
@Controller
@RequestMapping("/system/ytendereqe")
public class YtendereqeController extends BaseController
{
    private String prefix = "system/ytendereqe";

    @Autowired
    private IYtendereqeService ytendereqeService;

    @RequiresPermissions("system:ytendereqe:view")
    @GetMapping()
    public String ytendereqe()
    {
        return prefix + "/ytendereqe";
    }

    /**
     * 查询招标需求列表
     */
    @RequiresPermissions("system:ytendereqe:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Ytendereqe ytendereqe)
    {
        startPage();
        List<Ytendereqe> list = ytendereqeService.selectYtendereqeList(ytendereqe);
        return getDataTable(list);
    }

    /**
     * 导出招标需求列表
     */
    @RequiresPermissions("system:ytendereqe:export")
    @Log(title = "招标需求", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Ytendereqe ytendereqe)
    {
        logger.info("导出:{}",ytendereqe.getId());
        List<Ytendereqe> list = ytendereqeService.selectYtendereqeList(ytendereqe);
        ExcelUtil<Ytendereqe> util = new ExcelUtil<Ytendereqe>(Ytendereqe.class);
        return util.exportExcel(list, "招标需求数据");
    }

    /**
     * 导出招标需求列表
     */
    @RequiresPermissions("system:ytendereqe:export")
    @Log(title = "招标需求", businessType = BusinessType.EXPORT)
    @PostMapping("/exportData")
    @ResponseBody
    public AjaxResult exportData(Ytendereqe ytendereqe)
    {
        String[] ids = ytendereqe.getIds().toArray(new String[0]);
        List<Ytendereqe> list = ytendereqeService.selectYtendereqeByIds(ids);
        Ytendereqe ygd = new Ytendereqe();
        ygd.setId("填表说明");
        list.add(ygd);
        ExcelUtil<Ytendereqe> util = new ExcelUtil<Ytendereqe>(Ytendereqe.class);
        return util.exportExcel(list, "招标需求数据");
    }

    /**
     * 导入招标需求列表
     */
    @RequiresPermissions("system:ytendereqe:import")
    @Log(title = "招标需求", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Ytendereqe> util = new ExcelUtil<Ytendereqe>(Ytendereqe.class);
        List<Ytendereqe> list = util.importExcel(file.getInputStream());
        String message = ytendereqeService.importYtende(list, updateSupport);
        return AjaxResult.success(message);
    }

    @Anonymous
    @Log(title = "招标需求", businessType = BusinessType.IMPORT)
    @PostMapping("/importData2")
    @ResponseBody
    public List<Ytendereqe> importData2(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Ytendereqe> util = new ExcelUtil<Ytendereqe>(Ytendereqe.class);
        List<Ytendereqe> list = util.importExcel(file.getInputStream());
        String message = ytendereqeService.importYtende(list, updateSupport);
        return list;
    }

    /**
     * 下载模板
     */
    @RequiresPermissions("system:ytendereqe:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<Ytendereqe> util = new ExcelUtil<Ytendereqe>(Ytendereqe.class);
        return util.importTemplateExcel("招标需求数据");
    }

    /**
     * 新增招标需求
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存招标需求
     */
    @RequiresPermissions("system:ytendereqe:add")
    @Log(title = "招标需求", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Ytendereqe ytendereqe)
    {
        return toAjax(ytendereqeService.insertYtendereqe(ytendereqe));
    }

    /**
     * 修改招标需求
     */
    @RequiresPermissions("system:ytendereqe:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        Ytendereqe ytendereqe = ytendereqeService.selectYtendereqeById(id);
        mmap.put("ytendereqe", ytendereqe);
        return prefix + "/edit";
    }

    /**
     * 修改保存招标需求
     */
    @RequiresPermissions("system:ytendereqe:edit")
    @Log(title = "招标需求", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Ytendereqe ytendereqe)
    {
        return toAjax(ytendereqeService.updateYtendereqe(ytendereqe));
    }

    /**
     * 删除招标需求
     */
    @RequiresPermissions("system:ytendereqe:remove")
    @Log(title = "招标需求", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(ytendereqeService.deleteYtendereqeByUpdtick0s(ids));
    }

    /**
    * @Description: 查询各状态数量
    * @author: adam
    * @date: 2024/4/7 11:31
    * @param ytendereqe:
    * @Return: com.ruoyi.system.domain.Ytendereqe
    */
    @RequiresPermissions("system:ytendereqe:list")
    @PostMapping("/count")
    @ResponseBody
    public Ytendereqe count(Ytendereqe ytendereqe)
    {

        Ytendereqe ytenCount = ytendereqeService.selectYtendereqeCount(ytendereqe);
        return ytenCount;
    }

    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        logger.info("download:"+resource);
        // 本地资源路径
//        String localPath = Global.getProfile();
        // 数据库资源地址
        String downloadPath = resource;
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    @GetMapping("/download")
    public void download(String resource, HttpServletRequest request, HttpServletResponse response) throws IOException {
        downloadBlobsAsZip(resource,response);
    }

    @Anonymous
    @GetMapping("/downloadone")
    public void downloadone(String ynum,String yuuid, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try{
        Ytendereqe yt = new Ytendereqe();
        yt.setYnum0(ynum);
        yt.setYuuid(yuuid);
        List<Ytendereqe> ytenList = ytendereqeService.selectInitBlob(yt);
        if(ytenList==null || ytenList.size()==0){
            throw new Exception("数据不存在");
        }
        byte[] fileContent=null;
        String filename="";
        for (Ytendereqe yten: ytenList) {
            if (yten.getBlobData() == null || yten.getBlobData().length == 0) {
                throw new Exception("附件不存在");
            }
            fileContent=yten.getBlobData();
            filename=yten.getYfilename();
        }
            String contentType = null;
            if (filename.endsWith(".jpg") || filename.endsWith(".jpeg")) {
                contentType = "image/jpeg";
            } else if (filename.endsWith(".png")) {
                contentType = "image/png";
            } else if (filename.endsWith(".txt")) {
                contentType = "text/plain";
            }else if (filename.endsWith(".doc1") || filename.endsWith(".docx1")) {
                contentType = "application/vnd.ms-word"; // 或者application/vnd.openxmlformats-officedocument.wordprocessingml.document
            }else if (filename.endsWith(".doc") || filename.endsWith(".docx")) {
                contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; // 或者application/vnd.openxmlformats-officedocument.wordprocessingml.document
            } else if (filename.endsWith(".pdf")) {
                contentType = "application/pdf";
            }else if (filename.endsWith(".xls")|| filename.endsWith(".xlsx")) {
                contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }
            if (contentType == null) {
                contentType = "application/octet-stream";
            }

            String disposition = "attachment; filename=\"" + new String(filename.getBytes("UTF-8"), "ISO-8859-1") + "\"; "
                    + "filename*=UTF-8''" + URLEncoder.encode(filename, "UTF-8");
            response.setHeader("Content-Disposition", disposition);

            //String encodedFileName = MimeUtility.encodeWord(filename, "UTF-8", "B");
            //response.setHeader("Content-Disposition", "attachment; filename=\""+encodedFileName+"\"");
                // 设置响应头信息
        response.setContentType(contentType);
//        response.setHeader("Content-Disposition", contentDisposition); // 这里的ext应该是你的文件扩展名，如.zip, .pdf等

        // 将byte[]数组写入到输出流中
        try (OutputStream outputStream = response.getOutputStream()) {
            outputStream.write(fileContent);
            outputStream.flush(); // 确保所有数据都被写出
        }}catch (Exception e){

        }
    }

    /**
    * @Description: 首页数据
    * @author: adam
    * @date: 2024/6/25 14:08
    * @param ytendereqe:
    * @Return: com.ruoyi.system.domain.Ytendereqe
    */
    @Anonymous
    @PostMapping("/maindata")
    @ResponseBody
    public List<Ytendereqe> mainData(Ytendereqe ytendereqe)
    {
        List<Ytendereqe> maindata = ytendereqeService.selectInit(ytendereqe);
        return maindata;
    }

    @Anonymous
    @GetMapping("/initdownload")
    public void initDownload(String resource, HttpServletRequest request, HttpServletResponse response) throws IOException {
        downloadBlobsAsZip(resource,response);
    }

    @Anonymous
    @GetMapping("/exportByNum")
    public void exportByNum(String ynum,HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException {
        Ytendereqe yten = new Ytendereqe();
        yten.setYnum0(ynum);
        List<Ytendereqe> ytenList = ytendereqeService.selectYtendereqdList(yten);
        // 创建一个新的Excel工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("科新招标需求");
        for (int i = 0; i < 19; i++) { // 根据你的需要调整这个值
            sheet.setColumnWidth(i, 4000);
        }
        // 填充Excel数据（这里只是示例，你需要根据你的数据模型进行调整）
        int rowNum = 0;

        Row headerRow0 = sheet.createRow(rowNum++);
        headerRow0.createCell(0).setCellValue("发布日期");
        headerRow0.createCell(1).setCellValue("结束日期");
        headerRow0.createCell(2).setCellValue("材料编码");
        headerRow0.createCell(3).setCellValue("材料名称");
        headerRow0.createCell(4).setCellValue("规格型号");
        headerRow0.createCell(5).setCellValue("材质牌号");
        headerRow0.createCell(6).setCellValue("技术标准");
        headerRow0.createCell(7).setCellValue("需求数量");
        headerRow0.createCell(8).setCellValue("单位");
        headerRow0.createCell(9).setCellValue("交期");
        headerRow0.createCell(10).setCellValue("最终报价");
        headerRow0.createCell(11).setCellValue("附加技术要求");
        headerRow0.createCell(12).setCellValue("招标人");
        headerRow0.createCell(13).setCellValue("产品号");
        headerRow0.createCell(14).setCellValue("件号");
        headerRow0.createCell(15).setCellValue("锻件号");
        headerRow0.createCell(16).setCellValue("编号");
        headerRow0.createCell(17).setCellValue("行");
        headerRow0.createCell(18).setCellValue("备注");
        headerRow0.createCell(19).setCellValue("项目安排提示");
        headerRow0.createCell(20).setCellValue("零件名称");
        headerRow0.createCell(21).setCellValue("提料数量");
        headerRow0.createCell(22).setCellValue("提料单位");

        Row titleRow = sheet.createRow(rowNum++);
        titleRow.setHeightInPoints(39);
        Cell titleCell = titleRow.createCell(1);
        titleCell.setCellValue("科新招标需求");

        // 确定合并的起始列（cell所在的列）
        int firstColumn0 = titleCell.getColumnIndex();
        int lastColumn0 = 23;//firstColumn0 + 15; // 注意索引是从0开始的
        // 合并当前行的这几列
        int firstRow0 = titleCell.getRow().getRowNum();
        int lastRow0 = firstRow0; // 因为只合并一行，所以起始行和结束行相同
        sheet.addMergedRegion(new CellRangeAddress(firstRow0, lastRow0, firstColumn0, lastColumn0 - 1)); // 注意CellRangeAddress的列索引是到结束列的前一个
        // 自定义用户名为若依/单元格文字设置为红色
        CellStyle style20 = workbook.createCellStyle();
        style20.setWrapText(false);
        style20.setAlignment(HorizontalAlignment.CENTER);
        style20.setVerticalAlignment(VerticalAlignment.CENTER);
        Font dataFont20 = workbook.createFont();
        dataFont20.setFontName("宋体");
        dataFont20.setFontHeightInPoints((short) 18);
        dataFont20.setColor(IndexedColors.BLACK.index);
        dataFont20.setBold(true);
        style20.setFont(dataFont20);
        titleCell.setCellStyle(style20);

        // 图片文件路径
        String imagePath = "D:/WebIIS/zhaobiao/logo.png";
        // 加载图片文件
        FileInputStream fis = new FileInputStream(new File(imagePath));
        byte[] bytes = IOUtils.toByteArray(fis);
//        String staticPath = ServletUriComponentsBuilder.fromCurrentContextPath().path("/static/logo.png").build().toUriString();

        // 从类路径加载资源
//        String classPathFilePath = "/images/logo.png";
//        byte[] classPathContent = Files.readAllBytes(Paths.get(ClassLoader.getSystemResource(classPathFilePath).toURI()));
//        System.out.println("Content from classpath: " + classPathContent.length + " bytes");

//        workbook.addPicture(bytes,Workbook.PICTURE_TYPE_PNG);
        // 添加图片到工作簿
        int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);

        // 创建一个图片对象
        CreationHelper createHelper = workbook.getCreationHelper();
        ClientAnchor anchor = new XSSFClientAnchor(); // 设置位置
        anchor.setCol1(0);
        anchor.setRow1(1);
        anchor.setCol2(1);
        anchor.setRow2(2);

        Drawing<?> drawing = sheet.createDrawingPatriarch();
        Picture pict = drawing.createPicture(anchor, pictureIdx);
    if (1==1) {
        Row headerRow = sheet.createRow(rowNum++);
        headerRow.createCell(0).setCellValue("发布日期");
        headerRow.createCell(1).setCellValue("结束日期");
        headerRow.createCell(2).setCellValue("材料编码");
        headerRow.createCell(3).setCellValue("材料名称");
        headerRow.createCell(4).setCellValue("规格型号");
        headerRow.createCell(5).setCellValue("材质牌号");
        headerRow.createCell(6).setCellValue("技术标准");
        headerRow.createCell(7).setCellValue("需求数量");
        headerRow.createCell(8).setCellValue("单位");
        headerRow.createCell(9).setCellValue("交期");
        headerRow.createCell(10).setCellValue("报价（单价）");
        headerRow.createCell(11).setCellValue("附加技术要求");
        headerRow.createCell(12).setCellValue("招标人");
        headerRow.createCell(13).setCellValue("产品号");
        headerRow.createCell(14).setCellValue("件号");
        headerRow.createCell(15).setCellValue("锻件号");
        headerRow.createCell(16).setCellValue("编号");
        headerRow.createCell(17).setCellValue("行");
        headerRow.createCell(18).setCellValue("备注");
        headerRow.createCell(19).setCellValue("项目安排提示");
        headerRow.createCell(20).setCellValue("零件名称");
        headerRow.createCell(21).setCellValue("提料数量");
        headerRow.createCell(22).setCellValue("提料单位");

        // 创建一个CellStyle并设置背景颜色
//        CellStyle style = workbook.createCellStyle();
        // 创建一个CellStyle并设置背景颜色
        XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle();
        // 设置填充颜色为浅黄色（这里使用XSSFColor的静态方法，对于HSSFWorkbook，你可能需要自定义颜色索引）
        byte[] rgb = new byte[]{(byte) 128, (byte) 128, (byte) 128};
        XSSFColor myColor = new XSSFColor(rgb, null); // RGB for light yellow

        style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.index); // 注意：这假设了颜色已经被添加到了工作簿的调色板中
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 设置填充模式为实心
        style.setWrapText(true);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        Font dataFont = workbook.createFont();
        dataFont.setFontName("Arial");
        dataFont.setFontHeightInPoints((short) 10);
        dataFont.setColor(IndexedColors.WHITE.index);
        style.setFont(dataFont);

        XSSFCellStyle style_hide = (XSSFCellStyle) workbook.createCellStyle();
        style_hide.setHidden(true);


        for (int i = 0; i < 23; i++) {
            headerRow.getCell(i).setCellStyle(style);
        }
//        headerRow.getCell(16).setCellStyle(style_hide);
//        headerRow.getCell(17).setCellStyle(style_hide);

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        XSSFCellStyle styled = (XSSFCellStyle) workbook.createCellStyle();
        styled.setWrapText(true);
        styled.setAlignment(HorizontalAlignment.CENTER);
        styled.setVerticalAlignment(VerticalAlignment.CENTER);
        XSSFCellStyle styled_hide = styled;
        styled_hide.setHidden(true);
        for (Ytendereqe yte : ytenList) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(formatter.format(yte.getYdat0()));
            row.createCell(1).setCellValue(formatter.format(yte.getYdatend0()));
            row.createCell(2).setCellValue(yte.getYitm0());
            row.createCell(3).setCellValue(yte.getItmdes1());
            row.createCell(4).setCellValue(yte.getYggxx());
            row.createCell(5).setCellValue(yte.getYczph());
            row.createCell(6).setCellValue(yte.getYjsbz());
            row.createCell(7).setCellValue(yte.getYqty().toString());
            if (yte.getYhszl().compareTo(BigDecimal.valueOf(0)) > 0) {
                row.createCell(7).setCellValue(yte.getYhszl().toString());
            }
            row.createCell(8).setCellValue(yte.getStu());
            row.createCell(9).setCellValue(formatter.format(yte.getYjhq()));
            row.createCell(10).setCellValue("0");
            row.createCell(11).setCellValue(yte.getYfjjsyq());
            row.createCell(12).setCellValue(yte.getYzbr());
            row.createCell(13).setCellValue(yte.getYsbitm());
            row.createCell(14).setCellValue(yte.getYjh());
            row.createCell(15).setCellValue(yte.getYcjh());
            row.createCell(16).setCellValue(yte.getYnum0());
            row.createCell(17).setCellValue(yte.getYlin0());
            row.createCell(18).setCellValue("");
            row.createCell(19).setCellValue(yte.getYxmapts());
            row.createCell(20).setCellValue(yte.getYljdes());
            row.createCell(21).setCellValue(yte.getYtlqty());
            row.createCell(22).setCellValue(yte.getYtlstu());
            for (int i = 0; i < 23; i++) {
                row.getCell(i).setCellStyle(styled);
            }
//            row.getCell(16).setCellStyle(styled_hide);
//            row.getCell(17).setCellStyle(styled_hide);
        }
        Row footerRow = sheet.createRow(rowNum++);
        Cell cell = footerRow.createCell(0);
        cell.setCellValue("填表说明:1、板材’管材报价按重量报价，单位填写为元/Kg;2、锻件报价按单件报价，单位填写为元/件");

        // 确定合并的起始列（cell所在的列）
        int firstColumn = cell.getColumnIndex();
        int lastColumn = firstColumn + 23; // 注意索引是从0开始的
        // 合并当前行的这几列
        int firstRow = cell.getRow().getRowNum();
        int lastRow = firstRow; // 因为只合并一行，所以起始行和结束行相同
        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstColumn, lastColumn - 1)); // 注意CellRangeAddress的列索引是到结束列的前一个
        // 自定义用户名为若依/单元格文字设置为红色
        CellStyle style2 = workbook.createCellStyle();
        style2.setWrapText(false);
        style2.setAlignment(HorizontalAlignment.LEFT);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        Font dataFont2 = workbook.createFont();
        dataFont2.setFontName("Arial");
        dataFont2.setFontHeightInPoints((short) 10);
        dataFont2.setColor(IndexedColors.RED.index);
        style2.setFont(dataFont2);
        cell.setCellStyle(style2);
    }
        //隐藏列-编号/行
        sheet.setColumnHidden(16,true);
        sheet.setColumnHidden(17,true);
        sheet.setColumnWidth(16, 1);
        sheet.setColumnWidth(17, 1);
        //隐藏行
        headerRow0.setZeroHeight(true);

        String fileName = "科新招标需求"+ynum+".xlsx";
        String disposition = "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\"; "
                + "filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-Disposition", disposition);


        // 设置HTTP响应头
        //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        //String encodedFileName = MimeUtility.encodeWord("招标需求"+ynum+".xlsx", "UTF-8", "B");
        //response.setHeader("Content-Disposition", "attachment; filename=\""+encodedFileName+"\"");
        // 发送Excel文件到客户端
        try (OutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        }
        // 关闭工作簿
        workbook.close();
    }

    public byte[][] getBlobData(String ynum0) throws IOException {
        // 这里只是模拟数据，你应该从数据库查询并返回这些数据
        List<byte[]> blobDataList = new ArrayList<>();
        try {
            Ytendereqe yt = new Ytendereqe();
            yt.setYnum0(ynum0);
            List<Ytendereqe> ytenList = ytendereqeService.selectInitBlob(yt);
            if(ytenList==null){
                throw new Exception("数据不存在");
            }
            for (Ytendereqe yten: ytenList) {
                if (yten.getBlobData() == null || yten.getBlobData().length == 0) {
                    throw new Exception("附件不存在");
                }
                blobDataList.add(yten.getBlobData());
            }
            byte[][] blobDataArray = blobDataList.toArray(new byte[blobDataList.size()][]);
            return blobDataArray;
        }catch (Exception e){
            e.printStackTrace();
            throw new IOException("getBlobData失败:"+e.getMessage());
        }
    }

    /**
     * 加载招标需求列表树
     */
    @RequiresPermissions("system:ytendereqe:list")
    @GetMapping("/ytrqTreeData")
    @ResponseBody
    public List<Xtree> deptTreeData()
    {
        List<Xtree> xtrees = ytendereqeService.selectYtrqTree(new Ytendereqe());
        return xtrees;
    }

    public String[] getBlobFilenames(String ynum0) throws IOException {
        ArrayList<String> stringList = new ArrayList<>();
        try {
            Ytendereqe yt = new Ytendereqe();
            yt.setYnum0(ynum0);
            List<Ytendereqe> ytenList = ytendereqeService.selectInitBlob(yt);
            if(ytenList==null){
                throw new Exception("数据不存在");
            }
            for (Ytendereqe yten: ytenList) {
                stringList.add(yten.getYfilename());
            }
            String[] stringArray = stringList.toArray(new String[0]);
            return stringArray;
        }catch (Exception e){
            e.printStackTrace();
            throw new IOException("getBlobData失败:"+e.getMessage());
        }
    }

    public void downloadBlobsAsZip(String ynum0,HttpServletResponse response) throws IOException {
        byte[][] blobDataArray = getBlobData(ynum0);
        String[] filenames = getBlobFilenames(ynum0);

        // 检查blobDataArray和filenames的长度是否一致
        if (blobDataArray.length != filenames.length) {
            throw new IllegalArgumentException("blobDataArray and filenames must have the same length");
        }
        // 获取当前日期和时间
        LocalDateTime now = LocalDateTime.now();
        // 创建一个DateTimeFormatter对象来定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        // 使用formatter将日期时间转换为指定的格式
        String formattedDateTime = "KXJD"+now.format(formatter);
        // 设置HTTP响应头以发送ZIP文件
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename="+formattedDateTime+".zip");

        try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
            for (int i = 0; i < blobDataArray.length; i++) {
                byte[] blobData = blobDataArray[i];
                String filename = filenames[i];
                // 创建一个新的ZIP条目
                ZipEntry zipEntry = new ZipEntry(filename);
                zipOut.putNextEntry(zipEntry);
                // 写入BLOB数据到ZIP条目
                zipOut.write(blobData);
                // 完成ZIP条目的写入
                zipOut.closeEntry();
            }
            // 完成ZIP文件的写入
            zipOut.finish();
        }
    }
}
